package me.leon.ext.android

import android.Manifest.permission.VIBRATE
import android.content.Context
import android.os.Vibrator
import androidx.annotation.RequiresPermission
import me.leon.ext.Utils

/**
 * <pre> author: Blankj blog : http://blankj.com time : 2016/09/29 desc : utils about vibrate </pre>
 * *
 */
object VibrateUtils {

    private var vibrator: Vibrator? = null

    /**
     * Vibrate.
     *
     * Must hold `<uses-permission android:name="android.permission.VIBRATE" />`
     *
     * @param milliseconds The number of milliseconds to vibrate.
     */
    @RequiresPermission(VIBRATE)
    fun vibrate(milliseconds: Long) {
       getVibrator()?.vibrate(milliseconds)
    }

    /**
     * Vibrate.
     *
     * Must hold `<uses-permission android:name="android.permission.VIBRATE" />`
     *
     * @param pattern An array of longs of times for which to turn the vibrator on or off.
     * @param repeat The index into pattern at which to repeat, or -1 if you don't want to repeat.
     */
    @RequiresPermission(VIBRATE)
    fun vibrate(pattern: LongArray, repeat: Int) {
         getVibrator()?.vibrate(pattern, repeat)
    }

    /**
     * Cancel vibrate.
     *
     * Must hold `<uses-permission android:name="android.permission.VIBRATE" />`
     */
    @RequiresPermission(VIBRATE)
    fun cancel() {
        getVibrator()?.cancel()
    }

    private fun getVibrator(): Vibrator? {
        if (vibrator == null) {
            vibrator = Utils.app.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        }
        return vibrator
    }
}
